<template>
  <div>
    <page :footShow="changePage">
      <div slot="aside">
        <el-tabs type="card">
          <div class="cover-all"></div>
          <el-tab-pane label="组织机构">
            <unitTree :width="'100%'" @click="handleInUnitClick"></unitTree>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!--工具栏-->
      <div slot="toolbar">
        <el-form
          :inline="true"
          :model="filters"
          label-width="90px"
          label-position="right"
        >
          <el-form-item>
            <el-input
              v-model="filters.name"
              placeholder="账号名"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="btnSearch">
        <el-button @click="handleQuery('a')">查询</el-button>
        <el-button
          type="primary"
          :disabled="!hasPerm('sys:user:add')"
          @click="handleAdd"
          >新增</el-button
        >
      </div>
      <!--表格内容栏-->
      <div slot="content" class="contentH">
        <eidtuser
          v-if="!changePage"
          :dataForm="dataForm"
          :Gid="this.filters.GID"
          :operation="operation"
          :options="options"
          :pageResult="pageResult"
          @getMsg="handleQuery"
        ></eidtuser>
        <el-table
          :header-cell-style="{ background: '#e7eaf0', color: '#606266' }"
          :data="pageResult"
          stripe
          style="width: 100%"
          rowKey="id"
          v-loading="loading"
          @selection-change="handleSelectionChange"
          element-loading-text="加载中..."
          v-if="changePage"
        >
          <!-- <el-table-column prop="id" header-align="center" align="center" width="80" label="ID"></el-table-column> -->
          <el-table-column type="selection"></el-table-column>
          <table-tree-column
            prop="username"
            header-align="center"
            align="center"
            label="登录名"
          ></table-tree-column>
          <table-tree-column
            prop="name"
            header-align="center"
            align="center"
            label="账号名"
          ></table-tree-column>
          <table-tree-column
            prop="groupName"
            header-align="center"
            align="center"
            label="所属机构"
          ></table-tree-column>
          <table-tree-column
            prop="phone"
            header-align="center"
            align="center"
            label="电话"
          ></table-tree-column>
          <table-tree-column
            prop="mail"
            header-align="center"
            align="center"
            label="邮箱"
          ></table-tree-column>
          <el-table-column
            prop="status"
            header-align="center"
            align="center"
            label="启用状态"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.status == 2">无效</span>
              <span v-if="scope.row.status == 1">有效</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="inserttime"
            header-align="center"
            align="center"
            label="创建时间"
          ></el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="280"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button
                type="primary"
                :disabled="!hasPerm('sys:user:edit')"
                @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <!-- <el-button type="danger" :disabled='!hasPerm("sys:user:edit")' @click="handleStatus(scope.row)">禁用
              </el-button>-->
              <el-button
                type="danger"
                :disabled="!hasPerm('sys:user:delete')"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer">
        <!-- 批量删除 -->
        <el-button
          :disabled="selections.length === 0"
          type="danger"
          style="float: left"
          @click="batchDelete"
          >批量删除</el-button
        >
        <el-pagination
          layout="total, prev, pager, next, jumper"
          @current-change="refreshPageRequest"
          :current-page="pageRequest.page"
          :page-size="pageRequest.limit"
          :total="totalSize"
          style="float: right"
        ></el-pagination>
      </div>
      <!-- <kt-table :height="220" permsEdit="sys:role:edit" permsDelete="sys:role:delete" :highlightCurrentRow="true" :stripe="false"
		:data="pageResult" :columns="columns" :showBatchDelete="false" @handleCurrentChange="handleRoleSelectChange"
		@findPage="findPage" @handleEdit="handleEdit" @handleDelete="handleDelete">
      </kt-table>-->
      <!-- </el-col> -->
      <!--角色菜单，表格树内容栏-->
      <!-- <div class="menu-container" :v-if="true">
		<div class="menu-header">
			<span><B>角色菜单授权</B></span>
		</div>
		<el-tree :data="menuData" size="mini" show-checkbox node-key="id" :props="defaultProps"
			style="width: 100%;pading-top:20px;" ref="menuTree" :render-content="renderContent"
			v-loading="menuLoading" element-loading-text="拼命加载中" :check-strictly="true"
			@check-change="handleMenuCheckChange">
		</el-tree>
		<div style="float:left;padding-left:24px;padding-top:12px;padding-bottom:4px;">
			<el-checkbox v-model="checkAll" @change="handleCheckAll" :disabled="this.selectRole.id == null"><b>全选</b></el-checkbox>
		</div>
		<div style="float:right;padding-right:15px;padding-top:4px;padding-bottom:4px;">
			<kt-button :label="$t('action.reset')" perms="sys:role:edit" type="primary" @click="resetSelection" 
				:disabled="this.selectRole.id == null"/>
			<kt-button :label="$t('action.submit')" perms="sys:role:edit" type="primary" @click="submitAuthForm" 
				:disabled="this.selectRole.id == null" :loading="authLoading"/>
		</div>
      </div>-->
    </page>
  </div>
</template>
<script>
// import { hasPermission } from '@/permission/index.js'
import KtTable from "@/views/Core/KtTable";
import unitTree from "./comments/unitTree";
import KtButton from "@/views/Core/KtButton";
import TableTreeColumn from "@/views/Core/TableTreeColumn";
import { format } from "@/utils/datetime";
import eidtuser from "./comments/eidtuser";
export default {
  components: {
    unitTree,
    KtTable,
    KtButton,
    TableTreeColumn,
    eidtuser,
  },
  data() {
    return {
      //
      changePage: true,

      // 短信验证
      openMsg: false,
      // 要上传的图片
      dialogImageUrl: "",
      // 图片辉县列表
      fileList: [],
      // 图片上传
      dialogVisibleimg: false,
      // 要上传的图片
      loadimage: "",
      loading: false,
      asideShow: false,
      filters: {
        GID: "",
        name: "",
      },
      options: [],
      value: "",
      editLoading: false,
      dataFormRules: {
        name: [
          {
            required: true,
            message: "名称不能为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
        ],
        username: [
          {
            required: true,
            message: "用户名不能为空",
            trigger: "blur",
          },
        ],
      },

      // 新增编辑界面数据
      dataForm: {
        id: 0,
        name: "",
        username: "",
        phone: "",
        mail: "",
        password: "",
        role_id: "",
        defaultId: "",
        des: "",
        show_title: "",
        houtai_title: "",
        echart_title: "",
        imgs: [],
        photo: [],
        longitude: "",
        latitude: "",
        zooms: "", //地图大小
      },
      selections: [],
      pageResult: [],
      groupDataGID: "", //选择的组ID
      pageRequest: {
        page: 1,
        limit: 10,
      },
      totalSize: 0,
      dialogVisible: false,
      operation: false,
    };
  },
  methods: {
    //  hasPerms: function (perms) {
    //   // 根据权限标识和外部指示状态进行权限判断

    //   return hasPermission(perms) & !this.disabled

    // },
    // 获取分页数据
    handleQuery: function (val) {
      this.changePage = true;
      //this.$refs.outUnitTree.handleQuery();
      this.loading = true;
      //   this.pageRequest = Object.assign(this.filters)
      let params = {
        rows: {},
        where: this.filters,
        page: val ? "" : this.pageRequest.page,
        limit: val ? "" : this.pageRequest.limit,
      };

      let param = JSON.stringify(params);
      this.$api.user.findPage(param).then((res) => {
        if (res.code == 0) {
          this.loading = false;
          this.pageResult = res.data;
          this.pageResult.map((item) => {
            item.inserttime = this.$format(item.inserttime);
          });
          this.totalSize = res.count;
        } else {
          this.$message({
            message: "网络异常,请重试 " + res.msg,
            type: "error",
          });
        }
      });
    },
    refreshPageRequest(page) {
      this.pageRequest.page = page;
      this.handleQuery();
    },
    handleInUnitClick(data) {
      //   this.groupDataGID = data.GID;
      this.filters.GID = data.GID;
      //   this.pageRequest.name=data.name
      //   this.pageRequest.status = data.status;
      this.pageRequest.page = 1;
      this.handleQuery();
    },
    //设置权限
    handlePermission(row) {},
    handleSelectionChange(val) {
      this.selections = val;
    },

    // 删除
    handleDelete(data) {
      this.$confirm("确认删除选中记录吗？", "提示", {
        type: "warning",
      }).then(() => {
        // let params = this.getDeleteIds([], row);

        let params = {
          tbn: "authority_user",

          where: {
            _id: data._id,
          },
        };

        var aaa = JSON.stringify(params);
        this.$api.user.batchDelete(aaa).then((res) => {
          if (res.code == 0) {
            this.handleQuery();
            this.$message({
              message: "删除成功",
              type: "success",
            });
          } else {
            this.$message({
              message: "操作失败, " + res.msg,
              type: "error",
            });
          }
        });
      });
    },
    // 批量删除
    batchDelete() {
      this.$confirm("确认删除选中用户吗？", "提示", "warning").then(() => {
        let selLength = this.selections.length;
        let totalLength = this.pageResult.length;
        let isReduce = selLength == totalLength ? true : false;
        let params = this.selections
          .map((item) => {
            return item._id;
          })
          .join(",");
        let paramss = {
          tbn: "authority_user",

          where: {
            _id: params,
          },
        };

        var aaa = JSON.stringify(paramss);
        this.$api.user.batchDelete(aaa).then((res) => {
          if (res.code == 0) {
            this.$message.success("删除成功");
            if (isReduce) {
              this.pageRequest.page--;
            }
            this.handleQuery();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 显示新增界面
    handleAdd: function () {
      this.getRoleList(this.filters.GID);

      this.changePage = false;

      this.operation = true;
      this.dataForm = {
        userTypeId: "",
        defaultId: "",
        role_id: "",
        _id: "",
        GID: this.filters.GID,
        name: "",
        username: "",
        password: "",
        des: "",
        show_title: "",
        houtai_title: "",
        echart_title: "",
        phone: "",
        mail: "",
        imgs: [],
        photo: [],
        longitude: "",
        latitude: "",
        zooms: "", //地图大小
      };
    },
    // 显示编辑界面
    handleEdit: function (params) {
      if (!params.imgs) {
        params.imgs = [];
      } else {
        params.imgs = params.imgs.filter(function (n) {
          return n;
        });
      }
      if (!params.photo) {
        params.photo = [];
      } else {
        params.photo = params.photo.filter(function (n) {
          return n;
        });
      }
       // 这里需要对 userTypeId 进行初始化定义
        this.dataForm = Object.assign({ userTypeId: "" }, params);
        this.operation = false;
        this.changePage = false;
        this.getRoleList(params.GID);
    },
    getRoleList(GID) {
      let param = {
        where: {
          GID: GID,
        },
      };
      var aaa = JSON.stringify(param);
      this.$api.role.findPage(aaa).then((res) => {
        this.options = res.data;
        this.options.map((item) => {
          item._id = item._id.replace(/\"/g, "");
          // console.log(item._id)
        });
        // this.pageResult = res.data;
        //  this.totalSize=res.count
        // this.popupTreeData = this.getParentMenuTree(res.data);
        this.loading = false;
      });
    },

    // 获取数据
    findTreeData: function () {
      this.menuLoading = true;
      this.$api.menu.findMenuTree().then((res) => {
        this.menuData = res.data;
        this.menuLoading = false;
      });
    },
    // 角色选择改变监听
    handleRoleSelectChange(val) {
      if (val == null || val.val == null) {
        return;
      }
      this.selectRole = val.val;
      this.$api.role
        .findRoleMenus({
          roleId: val.val.id,
        })
        .then((res) => {
          this.currentRoleMenus = res.data;
          this.$refs.menuTree.setCheckedNodes(res.data);
        });
    },

    // 递归全选
    checkAllMenu(menuData, allMenus) {
      menuData.forEach((menu) => {
        allMenus.push(menu);
        if (menu.children) {
          this.checkAllMenu(menu.children, allMenus);
        }
      });
    },
    // 编辑添加图片
    async upLoad(param) {
      let that = this;
      this.loadimage = "";
      var imgup = "";
      await this.getBase64(param.file).then((res) => {
        imgup = res;
      });
      var paramd = {
        img: imgup,
      };
      this.$api.imgAdd.addimgPer(paramd).then((res) => {
        // this.loadimage = res.id;
        that.dataForm.imgs.push(res.id);
        that.dataForm.photo.push(res.id);
        // console.log(that.dataForm);
      });
    },
  },
  mounted() {
    this.handleQuery();
  },
};
</script>
<style lang="scss" scoped>
.contentH {
  height: 100%;
  overflow: hidden;
}
.menu-container {
  margin-top: 10px;
}

.menu-header {
  padding-left: 8px;
  padding-bottom: 5px;
  text-align: left;
  font-size: 16px;
  color: rgb(20, 89, 121);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
.mapj {
  /* display: ; */
  display: flex;
  justify-content: start;
  span {
    white-space: nowrap;
    display: block;
    width: 50px;
  }
  .mapinp {
    width: 37%;
  }
  .mapnum {
    width: 16%;
  }
}
</style>
